package com.wrupple.muba.desktop.client.bootstrap.state.impl;

import java.util.ArrayList;
import java.util.Collection;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.wrupple.muba.common.domain.ApplicationItem;
import com.wrupple.muba.common.domain.RawSlice;
import com.wrupple.muba.common.domain.Slice;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.desktop.client.bootstrap.state.RegisterLoadedPlaces;
import com.wrupple.muba.desktop.client.module.DesktopPlaceHistoryMapper;
import com.wrupple.muba.desktop.domain.DesktopDescriptor;
import com.wrupple.muba.desktop.domain.DesktopLoadingStateHolder;

public class RegisterLoadedPlacesImpl implements RegisterLoadedPlaces {
	
	private DesktopPlaceHistoryMapper historyMapper ;
	
	
	@Inject
	public RegisterLoadedPlacesImpl(DesktopPlaceHistoryMapper historyMapper) {
		super();
		this.historyMapper = historyMapper;
	}



	@Override
	public void start(DesktopLoadingStateHolder parameter, StateTransition<DesktopLoadingStateHolder> onDone,EventBus eventBus) {
		parameter.setDesktopDescriptor(validar(parameter.getDesktopDescriptor()));
		onDone.setResultAndFinish(parameter);
	}
	

	 DesktopDescriptor validar(DesktopDescriptor result) {
		GWT.log("Validating Slices");
		Collection<RawSlice> slices = result.getRawSlices();
		for (RawSlice slice : slices) {
			validarSlice(slice, result);
		}
		return result;
	}
	
	 void validarSlice(RawSlice rawSlice, DesktopDescriptor result) {
		Slice configuredSlice;
		ArrayList<ApplicationItem> items;
		if (rawSlice != null) {
			GWT.log("Validating Slice " + rawSlice.getDefaultName());
			configuredSlice = rawSlice.getSlice();
			if (configuredSlice == null) {
				GWT.log("Slice Not Configured ");
			} else {
				if (configuredSlice.getItems() != null) {
					GWT.log("Validating Slice Items");
					items = configuredSlice.getItems();
					for (ApplicationItem item : items) {
						validarItem(item, configuredSlice, rawSlice);
					}
				}
			}

		} else {
			GWT.log("null Slice found");
		}
	}
	
	private void validarItem(ApplicationItem item, Slice app, RawSlice rawapp) {
		registerItemId(item);

		if (!(item.getChildren() == null || item.getChildren().size() == 0)) {
			for (ApplicationItem i : item.getChildren()) {
				validarItem(i, app, rawapp);
			}
		}
	}
	
	private void registerItemId(ApplicationItem item) {
		this.historyMapper.registerPlace(item);
	}

}
